﻿// See https://aka.ms/new-console-template for more information
using System;
using System.Threading.Tasks;

namespace NamedPipeServer
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("=== Named Pipe Server Demo ===");
            Console.WriteLine();

            // Create server instance
            var server = new NamedPipeServerManager("UnityWpfPipe", 5);

            // Subscribe to server events
            server.OnInfo += message => Console.WriteLine($"[INFO] {message}");
            server.OnError += message => Console.WriteLine($"[ERROR] {message}");
            server.OnClientConnected += message => Console.WriteLine($"[CONNECT] {message}");
            server.OnClientDisconnected += message => Console.WriteLine($"[DISCONNECT] {message}");
            server.OnMessageReceived += message => Console.WriteLine($"[MESSAGE] {message}");

            // Handle Ctrl+C gracefully
            Console.CancelKeyPress += (sender, e) =>
            {
                e.Cancel = true;
                Console.WriteLine("\nShutting down server...");
                server.Stop();
            };

            try
            {
                // Start the server
                Console.WriteLine("Starting server...");
                var serverTask = server.StartAsync();

                Console.WriteLine("Server is running. Press Ctrl+C to stop...");
                Console.WriteLine("Clients can connect and send messages.");
                Console.WriteLine("Special commands: 'ping', 'time', 'disconnect'");
                Console.WriteLine();

                // Wait for server to complete (or be cancelled)
                await serverTask;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Server failed: {ex.Message}");
            }
            finally
            {
                // Clean up
                server.Dispose();
                Console.WriteLine("Server stopped. Press any key to exit...");
                Console.ReadKey();
            }
        }
    }
}
